package navgtor

import (
	"bufio"
	"os"
	"path/filepath"
)

func GenNav() error {
	// 获取可执行程序的路径
	ePath, err := os.Executable()
	if err != nil {
		return err
	}

	dir, _ := filepath.Split(ePath)
	// dir := "C:/Users/Chace.cen/Desktop/wiki"
	libPath := dir + "/" + "library"
	root, err := genNavTree(libPath)
	if err != nil {
		return err
	}

	mdPath := libPath + "/" + "$navigation.md.tmp"
	f, err := os.Create(mdPath)
	if err != nil {
		return err
	}

	wt := bufio.NewWriter(f)
	err = startParse(root, wt)
	if err != nil {
		return err
	}

	f.Close()

	if err := os.Remove(libPath + "/$navigation.md"); err != nil {
		return err
	}

	if err := os.Rename(mdPath, libPath+"/$navigation.md"); err != nil {
		return err
	}

	return nil
}
